/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2025 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "command.h"
#include "stdio.h"
#include "bsp_dwt.h"
#include "BMI088driver.h"
#include "mahony_filter.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
extern SPI_HandleTypeDef hspi1; // 声明imuSPI句柄
extern struct MAHONY_FILTER_t imu_filter;
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

uint8_t rx_data[256] = {0};
uint32_t H_cnt = 1;
static char uart1_tx_buf[256];
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_NVIC_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
float gyro[3], accel[3], temp;
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */
  
  /* 初始化DWT计时模块：参数为CPU主频的MHz */
  DWT_Init(150);

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  SystemCoreClockUpdate();
  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USART1_UART_Init();
  MX_SPI1_Init();
  MX_TIM2_Init();
  MX_TIM1_Init();

  /* Initialize interrupts */
  MX_NVIC_Init();
  /* USER CODE BEGIN 2 */
  // DWT_Init(168);
  // HAL_UARTEx_ReceiveToIdle_DMA(&huart1, rx_data, sizeof(rx_data));
  // __HAL_DMA_DISABLE_IT(huart1.hdmarx, DMA_IT_HT);

  printf("BMI088_init() begin\r\n ");
  HAL_Delay(1);
  BMI088_Init(&hspi1, 0);
  mahony_init(&imu_filter, 1.0f, 0.002f, 0.002f);
  printf("BMI088_init done\r\n");
  HAL_TIM_Base_Start_IT(&htim1);

  /* 使用DWT测时，不打印，仅保留变量用于调试 */
    static uint32_t dwt_last = 0;      /* 上次CYCCNT计数 */
    static float dt_s = 0;     /* 秒，兼容原逻辑 */
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */

  while (1)
  {

    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    // BMI088read(gyro, accel, &temp);
    if (g_onesecond_flag)
    {
      
      BMI088_Read(&BMI088);

      /* 4. 调用 Mahony */
      Axis3f gyro = {.x = BMI088.Gyro[0],
                    .y = BMI088.Gyro[1],
                    .z = BMI088.Gyro[2]};
      Axis3f acc = {.x = BMI088.Accel[0],
                    .y = BMI088.Accel[1],
                    .z = BMI088.Accel[2]};
      mahony_input(&imu_filter, gyro, acc);

      /* 5. 更新 */
      mahony_update(&imu_filter);
      mahony_output(&imu_filter); // 调用输出函数

      /* 6. 打印角度值（度）dma */
      // printf("pitch/roll/yaw %d: %f, %f, %f\r\n",H_cnt, imu_filter.pitch*RAD2DEG, imu_filter.roll*RAD2DEG, imu_filter.yaw*RAD2DEG);
      // printf("gyro/accel: %f, %f, %f,%f, %f, %f,", BMI088.Gyro[0], BMI088.Gyro[1], BMI088.Gyro[2], BMI088.Accel[0], BMI088.Accel[1], BMI088.Accel[2]);
      // printf("%f, %f, %f, %f\r\n", imu_filter.q0, imu_filter.q1, imu_filter.q2, imu_filter.q3);

      int dma_len = 0;
      dma_len += snprintf(uart1_tx_buf + dma_len, sizeof(uart1_tx_buf) - dma_len,
                          "gyro/accel: %f, %f, %f,%f, %f, %f,",
                          BMI088.Gyro[0], BMI088.Gyro[1], BMI088.Gyro[2],
                          BMI088.Accel[0], BMI088.Accel[1], BMI088.Accel[2]);
      dma_len += snprintf(uart1_tx_buf + dma_len, sizeof(uart1_tx_buf) - dma_len,
                          "%f, %f, %f, %f\r\n",
                          imu_filter.q0, imu_filter.q1, imu_filter.q2, imu_filter.q3);
      if (dma_len > 0)
      {
        HAL_UART_Transmit_DMA(&huart1, (uint8_t *)uart1_tx_buf, (uint16_t)dma_len);
      }
      
      g_onesecond_flag = 0;
      
      dt_s = DWT_GetDeltaT(&dwt_last)*1000; /* ms */
      
      // DMA串口发送延迟时间
      // int tx_len = sprintf(uart1_tx_buf, "time: %lu ms\r\n", deltatime);
      // if (tx_len > 0)
      // {
      //   HAL_UART_Transmit_DMA(&huart1, (uint8_t *)uart1_tx_buf, (uint16_t)tx_len);
      // }

    }
		H_cnt++;

    
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV2;
  RCC_OscInitStruct.PLL.PLLN = 75;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }

  /** Enables the Clock Security System
  */
  HAL_RCC_EnableCSS();
}

/**
  * @brief NVIC Configuration.
  * @retval None
  */
static void MX_NVIC_Init(void)
{
  /* DMA1_Channel1_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 1, 0);
  HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
  /* DMA1_Channel2_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA1_Channel2_IRQn, 1, 0);
  HAL_NVIC_EnableIRQ(DMA1_Channel2_IRQn);
  /* USART1_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(USART1_IRQn, 1, 0);
  HAL_NVIC_EnableIRQ(USART1_IRQn);
}

/* USER CODE BEGIN 4 */

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
  if (huart->Instance == USART1)
  {
    // ???DMA????????????????????
    static const char *msg = "Receive:";
    HAL_UART_Transmit(&huart1, (uint8_t *)msg, strlen(msg), 1);
    HAL_UART_Transmit_DMA(&huart1, rx_data, Size);
    // ????????????????Ex???????????????????
    HAL_UARTEx_ReceiveToIdle_DMA(&huart1, rx_data, sizeof(rx_data));
    // ???DMA????????锟斤�???HAL?????????????????????????????锟斤�??????
    __HAL_DMA_DISABLE_IT(huart1.hdmarx, DMA_IT_HT);
  }
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
